<?php
namespace app\wap\controller;

class Answer extends Base{

	// 回答提交
	public function submit(){
		// 设置需要登录才能访问
		$this->user_id(true);
		$ask_id = $this->_get('ask_id', '对不起，您的操作有误！');
		$info   = model('Ask')->find($ask_id);
		if(!$info['status'] || $info['is_delete'] == 1){
			$this->error('问题不存在或已关闭！');
		}
		if($this->isPost()){
			$model = model('AskAnswer');
			$post_data['content']      = $this->_post('content', '请填写您要回复的答案！');
			$post_data['is_anonymous'] = $this->_post('is_anonymous', '', 0);
			$post_data['ask_id']       = $ask_id;
			$post_data['ask_user_id']  = $info['user_id'];
			$post_data['module']       = $info['module'];
			$post_data['user_id']      = $this->_user_id;
			$post_data['create_time']  = time();
			if($model->create($post_data, true) !== false){
				$answer_id = $model->getLastInsID();
				model('Ask')->updateAnswerNum($ask_id);
				// 更新用户回答数量
				model('UserData')->update_user_data($this->_user_id, 'answer_num');

				// 消息推送
				model('Message')->ask_answer_push($answer_id, 'answer_submit', $post_data['is_anonymous'] ? '-1' : $this->_user_id);
				
				$this->success('回答成功', url('Question/detail', array('ask_id' => $ask_id)));
			} else {
				$this->error('添加失败！');
			}
		}
	}

	// 答案点赞
	public function praise(){
		// 设置需要登录才能访问
		$this->user_id(true);
		$answer_id = $this->_get('answer_id', '对不起，您的操作有误！');

		$model = model('User');
		$reid  = $model->set_fav('AskAnswer', 'praise_num', 'answer_id', $this->_user_id, $answer_id, 'ask_answer_praise');
		if($reid == 1){
			// 消息推送
			model('Message')->ask_answer_push($answer_id, 'praise', $this->_user_id);
		}
		$data['node_id'] = 'answer-id-' . $answer_id;
		$data['node_data']['praise_num'] = $model->_total_fav_num;
		
		$this->success('', '', $data);
	}

	public function set_best(){
		// 设置需要登录才能访问
		$this->user_id(true);
		$answer_id = $this->_get('answer_id', '对不起，您的操作有误！');
		if(model('AskAnswer')->set_best($answer_id, $this->_user_id)){
			$this->success('设置成功！');
		}else{
			$this->error(model('AskAnswer')->tips_info);
		}
	}
}